package third;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;

/**
 * <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-10 15:44
 * @since 1.0.0
 */
public final class HttpClientTools {

    private static final int SOCKET_TIME = 30000;
    private static final int CONNECT_TIME = 3000;

    private static final String PROXY_HOST = "10.37.235.10";
    private static final int PROXY_PORT = 8080;

    private HttpClientTools() {
    }

    /**
     * 创建Https请求客户端
     *
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient createClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(
                null, new TrustSelfSignedStrategy()).build();
        SSLConnectionSocketFactory sslf = new SSLConnectionSocketFactory(
                sslContext, new String[]{"TLSv1"}, null,
                // SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()
        );
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslf).build();
        return client;
    }

    /**
     * 创建Get请求
     *
     * @param url
     * @return
     */
    public static HttpUriRequest buildHttpGet(String url) {
        HttpGet request = new HttpGet(url);
        RequestConfig config = RequestConfig.custom().build();
        request.setConfig(config);
        return request;
    }

    /**
     * 创建代理Get请求
     *
     * @param url
     * @param proxyHost 代理地址
     * @param proxyPort 代理端口
     * @return
     */
    public static HttpUriRequest buildProxyHttpGet(String url) {
        HttpGet request = new HttpGet(url);
        request.setConfig(RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIME)
                .setConnectTimeout(CONNECT_TIME)
                .setProxy(new HttpHost(PROXY_HOST, PROXY_PORT, null))
                //.setCookieSpec(COOKIE)
                .build());
        return request;
    }
}
